package com.iraytek.rtsplib;

import android.content.Context;
import android.graphics.ImageFormat;
import android.media.MediaCodec;

import java.nio.ByteBuffer;

import pedro.encoder.Frame;
import pedro.encoder.video.FormatVideoEncoder;
import pedro.encoder.video.GetVideoData;
import pedro.encoder.video.VideoEncoder;
import pedro.rtsp.rtsp.Protocol;
import pedro.rtsp.rtsp.RtspClient;
import pedro.rtsp.utils.ConnectCheckerRtsp;

/**
 * used for pulling stream
 */
public class ClientEncodeManager extends BaseEncodeManager implements DataCallback<byte[]> {
    protected RtspClient client;
    private String url;

    public ClientEncodeManager(Context context, ConnectCheckerRtsp checkerRtsp) {
        super(context);
        client = new RtspClient(checkerRtsp);
        setVideoEncodeFormat(FormatVideoEncoder.YUV420Dynamical);
    }

    /**
     * Set protocol for data transfer
     *
     * @param protocol TCP or UDP, default is TCP
     */
    public void setProtocol(Protocol protocol) {
        client.setProtocol(protocol);
    }

    @Override
    protected VideoEncoder createVideoEncoder(GetVideoData getVideoData) {
        return new CameraVideoEncoder(getVideoData);
    }

    @Override
    protected void prepareAudioRtp(boolean isStereo, int sampleRate) {
        client.setIsStereo(isStereo);
        client.setSampleRate(sampleRate);
    }

    @Override
    protected void getAacDataRtp(ByteBuffer aacBuffer, MediaCodec.BufferInfo info) {
        client.sendAudio(aacBuffer, info);
    }

    @Override
    protected void onSpsPpsVpsRtp(ByteBuffer sps, ByteBuffer pps, ByteBuffer vps) {
        client.setSPSandPPS(sps, pps, vps);
    }

    @Override
    protected void getVideoDataRtp(ByteBuffer buffer, MediaCodec.BufferInfo info) {
        client.sendVideo(buffer, info);
    }

    @Override
    protected void startStreamRtp(String url) {//eg "rtsp://10.10.25.223:8080/rtspbase/video"
        this.url = url;
        client.connect(url);
    }

    @Override
    protected void stopStreamRtp() {
        client.disconnect();
    }

    @Override
    public String getRtspAddress() {
        return url;
    }


    @Override
    public void onDataChange(byte[] data) {
        if (isStreaming() || recording) {
            Frame frame = new Frame(data, 0, false, ImageFormat.NV21);
            videoEncoder.inputYUVData(frame);
        }
    }
}
